import AMapLoader from '@amap/amap-jsapi-loader';
export class Amap {
    private AMap: any;
    private geocoder: any;
    private geolocation: any;
    constructor(config: any, callback?: Function) {
        if (config.amap_web_key && (config.amap_js_code || config.amap_service_host)) {
            if (config.amap_service_host) {
                globalThis._AMapSecurityConfig = { serviceHost: config.amap_service_host };
            }else if (config.amap_js_code) {
                globalThis._AMapSecurityConfig = { securityJsCode: config.amap_js_code };
            }
            AMapLoader.load({
                key: config.amap_web_key, // 申请好的Web端开发者Key，首次调用 load 时必填
                version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
                plugins: [], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
            })
                .then((AMap) => {
                    this.AMap = AMap;
                    typeof callback === 'function' && callback();
                })
                .catch((e) => {
                    console.log(e);
                });
        }
    }
    isReady() {
        return !!this.AMap;
    }
    usePlugin(plugin: string, options?: any) {
        return new Promise((resolve, reject) => {
            if (!this.AMap) {
                reject('AMap is not ready');
            }
            this.AMap.plugin(`AMap.${plugin}`, () => {
                const instance = new this.AMap[plugin](options);
                resolve(instance);
            });
        });
    }
    createMap(id: string) {
        return new Promise((resolve, reject) => {
            if (!this.AMap) {
                return reject('AMap is not ready');
            }
            const map = new this.AMap.Map(id, {
                // 设置地图容器id
                viewMode: "2D",
                zoom: 15
            });
            resolve(map);
        });
    }

    get Map() {
        return this.AMap;
    }

    createMarker(map: any, lnglat: any) {
        return new Promise((resolve, reject) => {
            if (!this.AMap) {
                return reject('AMap is not ready');
            }
            this.AMap.plugin('AMap.MoveAnimation', () => {
                const center = map.getCenter();
                const labelMarker = new this.AMap.LabelMarker({
                    position: [center.lng, center.lat],
                    opacity: 1,
                    zIndex: 2,
                    icon: {
                        image: 'static/icons/location.png',
                        anchor: 'bottom-center',
                        size: [30, 29],
                        clipOrigin: [0, 0],
                        clipSize: [87, 86]
                    }
                });
                const labelsLayer = new this.AMap.LabelsLayer({
                    collision: true,
                });
                labelsLayer.add(labelMarker);
                map.add(labelsLayer);
                if (lnglat) {
                    labelMarker.moveTo(lnglat);
                    map.setCenter(lnglat);
                }
                resolve(labelMarker);
            });
        });
    }
    getCurrentPosition(option?: any) {
        return new Promise((resolve, reject) => {
            if (!this.AMap) {
                return reject('geolocation is not ready');
            }
            if(this.geolocation){
                this.geolocation.getCurrentPosition((status: string, result: any) => {
                    if (status == 'complete') {
                        resolve(result);
                    } else {
                        reject(result);
                    }
                });
            }else{
                this.AMap.plugin("AMap.Geolocation", () => {
                    this.geolocation = new this.AMap.Geolocation({
                        enableHighAccuracy: true, // 是否使用高精度定位，默认：true
                        timeout: 10000, // 设置定位超时时间，默认：无穷大
                        offset: [10, 20],  // 定位按钮的停靠位置的偏移量
                        panToLocation: true,  //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
                        zoomToAccuracy: true,  //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
                        position: 'RT', //  定位按钮的排放位置,  RB表示右下
                        showMarker: false, //  定位成功后在定位到的位置显示点标记，默认：true
                        showCircle: false, //  定位成功后用圆圈表示定位精度范围，默认：true
                    })
                    this.geolocation.getCurrentPosition((status: string, result: any) => {
                        if (status == 'complete') {
                            resolve(result);
                        } else {
                            reject(result);
                        }
                    });
                });
            }
        });
    }
    getPosition(address: string) {
        return new Promise((resolve, reject) => {
            if (!this.AMap) {
                return reject('geocoder is not ready');
            }
            if(this.geocoder){
                this.geocoder.getLocation(address, (status: string, result: any) => {
                    if (status == 'complete' && result.info === 'OK') {
                        resolve(result);
                    } else {
                        reject(result);
                    }
                });
            }else{
                this.AMap.plugin('AMap.Geocoder', () => {
                    this.geocoder = new this.AMap.Geocoder()
                    this.geocoder.getLocation(address, (status: string, result: any) => {
                        if (status == 'complete' && result.info === 'OK') {
                            resolve(result);
                        } else {
                            reject(result);
                        }
                    });
                })
            }
        });
    }
    getAddress(lnglat: any) {
        return new Promise((resolve, reject) => {
            if (!this.AMap) {
                return reject('geocoder is not ready');
            }
            if(this.geocoder){
                this.geocoder.getAddress(lnglat, (status: string, result: any) => {
                    if (status == 'complete' && result.info === 'OK') {
                        let data = result.regeocode;
                        const formattedAddress = data.formattedAddress;
                        const addressComponent = data.addressComponent;
                        data.desc = formattedAddress
                            .replace(addressComponent.province + addressComponent.city + addressComponent.district + addressComponent.township, '');
                        resolve(data);
                    } else {
                        reject(result);
                    }
                });
            }else{
                this.AMap.plugin('AMap.Geocoder', () => {
                    this.geocoder = new this.AMap.Geocoder()
                    this.geocoder.getAddress(lnglat, (status: string, result: any) => {
                        if (status == 'complete' && result.info === 'OK') {
                            let data = result.regeocode;
                            const formattedAddress = data.formattedAddress;
                            const addressComponent = data.addressComponent;
                            data.desc = formattedAddress
                                .replace(addressComponent.province + addressComponent.city + addressComponent.district + addressComponent.township, '');
                            resolve(data);
                        } else {
                            reject(result);
                        }
                    });
                })
            }
        });
    }
}